package com.laolei.eureka.zuul.config;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;

public class PreFilter extends ZuulFilter {

	private static Logger log = LoggerFactory.getLogger(PreFilter.class);

	@Override
	public String filterType() {
		return "pre";
	}

	@Override
	public int filterOrder() {
		return 0;
	}

	@Override
	public boolean shouldFilter() {
		return true;
	}

	@Override
	public Object run() {
		RequestContext ctx = RequestContext.getCurrentContext();
		HttpServletRequest request = ctx.getRequest();

		log.info("{} 方式请求 {}", request.getMethod(), request.getRequestURL().toString());

		String token = request.getParameter("token");
		if (token == null) {
			log.warn("token 不可以为空，请求被拦截");
			ctx.setSendZuulResponse(false);
			ctx.setResponseStatusCode(401);
			return null;
		} else if (token.indexOf("baidu") != -1) {
			log.warn("请求被转发到百度");
			try {
				ctx.getResponse().sendRedirect("http://www.baidu.com");
			} catch (IOException e) {
			}
			ctx.setSendZuulResponse(false);
			ctx.setResponseStatusCode(301);

			return null;
		}
		log.info("access token ok");
		return null;
	}

}
